'use client';

import { useState, useMemo, useRef, useEffect } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { VideoType } from '@/lib/video/video-service';

interface EnhancedFilterProps {
  currentTypeId: number;
  allTypes: VideoType[];
  years: string[];
  areas: string[];
  selectedYears: string[];
  selectedAreas: string[];
  selectedTypes?: number[];
  sortBy: string;
}

// 定义年份处理结果的类型
interface ProcessedYears {
  recent: string[];
  hasEarlier: boolean;
  earliestYear: string | null;
  allEarlierYears: string[];
}

export default function EnhancedFilter({
  currentTypeId,
  allTypes,
  years,
  areas,
  selectedYears = [],
  selectedAreas = [],
  selectedTypes = [],
  sortBy = 'newest',
}: EnhancedFilterProps) {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  
  // 滚动容器引用和滚动状态
  const scrollContainerRefs = useRef<Record<string, HTMLDivElement | null>>({});
  const [scrollStates, setScrollStates] = useState<Record<string, {canScrollLeft: boolean; canScrollRight: boolean}>>({});
  
  // 处理年份筛选
  const processedYears = useMemo<ProcessedYears>(() => {
    if (!years.length) return {
      recent: [],
      hasEarlier: false,
      earliestYear: null,
      allEarlierYears: []
    };
    
    // 获取当前年份
    const currentYear = new Date().getFullYear();
    
    // 生成从当前年份开始往前9年的年份数组
    const recentYears = [];
    for (let i = 0; i < 9; i++) {
      recentYears.push((currentYear - i).toString());
    }
    
    // 所有年份按降序排列
    const sortedYears = [...years].sort((a, b) => parseInt(b) - parseInt(a));
    
    // 找出比最近9年更早的年份
    const earlierYears = sortedYears.filter(year => parseInt(year) < (currentYear - 8));
    
    // 最终处理结果
    const result = {
      recent: recentYears,
      hasEarlier: earlierYears.length > 0,
      earliestYear: earlierYears.length > 0 ? earlierYears[earlierYears.length - 1] : null,
      allEarlierYears: earlierYears,
    };
    
    return result;
  }, [years]);
  
  // 获取当前分类和子分类
  const childTypes = allTypes.filter(type => type.parentId === currentTypeId);
  
  // 构建筛选URL
  const buildFilterUrl = (yearsParam?: string[], areasParam?: string[], typesParam?: number[], sortParam?: string, yearLessThan?: string, yearGreaterThan?: string) => {
    const params = new URLSearchParams(searchParams.toString());
    
    // 清除旧的筛选参数
    params.delete('year');
    params.delete('area');
    params.delete('type');
    params.delete('yearLessThan');
    params.delete('yearGreaterThan');
    
    // 设置年份参数（多选）
    if (yearsParam && yearsParam.length > 0) {
      yearsParam.forEach(year => {
        params.append('year', year);
      });
    }
    
    // 设置年份小于参数
    if (yearLessThan) {
      params.set('yearLessThan', yearLessThan);
    }
    
    // 设置年份大于参数
    if (yearGreaterThan) {
      params.set('yearGreaterThan', yearGreaterThan);
    }
    
    // 设置地区参数（多选）
    if (areasParam && areasParam.length > 0) {
      areasParam.forEach(area => {
        params.append('area', area);
      });
    }
    
    // 设置类型参数（多选）
    if (typesParam && typesParam.length > 0) {
      typesParam.forEach(typeId => {
        params.append('type', typeId.toString());
      });
    }
    
    // 设置排序参数
    if (sortParam) {
      params.set('sort', sortParam);
    } else if (sortBy) {
      params.set('sort', sortBy);
    }
    
    // 确保保留页码参数 - 重置筛选条件时应该回到第一页
    params.delete('page');
    
    // 处理pathname，确保它带有.html后缀
    const normalizedPathname = pathname.replace(/\.html$/, '');
    const htmlPathname = `${normalizedPathname}.html`;
    return `${htmlPathname}?${params.toString()}`;
  };

  // 处理筛选选项的切换
  const toggleYear = (year: string) => {
    // 特殊处理"更早"按钮
    if (year === 'earlier') {
      // 检查是否已经选择了"更早"选项
      const isEarlierSelected = searchParams.has('yearLessThan');
      
      if (isEarlierSelected) {
        // 如果已经选择了"更早"，取消选择
        router.push(buildFilterUrl(selectedYears, selectedAreas, selectedTypes, sortBy, undefined, searchParams.get('yearGreaterThan') || undefined));
      } else {
        // 如果还没有选择"更早"，添加"更早"筛选
        // 获取最近年份列表中的最小年份作为yearLessThan参数
        const minRecentYear = processedYears.recent.length > 0 ? 
          processedYears.recent[processedYears.recent.length - 1] : 
          new Date().getFullYear().toString();
        
        // 保留已选择的年份，添加yearLessThan参数
        router.push(buildFilterUrl(selectedYears, selectedAreas, selectedTypes, sortBy, minRecentYear, searchParams.get('yearGreaterThan') || undefined));
      }
      return;
    }
    
    // 特殊处理"最新"按钮（新增）
    if (year === 'latest') {
      // 检查是否已经选择了"最新"选项
      const isLatestSelected = searchParams.has('yearGreaterThan');
      
      if (isLatestSelected) {
        // 如果已经选择了"最新"，取消选择
        router.push(buildFilterUrl(selectedYears, selectedAreas, selectedTypes, sortBy, searchParams.get('yearLessThan') || undefined, undefined));
      } else {
        // 如果还没有选择"最新"，添加"最新"筛选
        // 获取最近年份列表中的最大年份作为yearGreaterThan参数
        const maxRecentYear = processedYears.recent.length > 0 ? 
          processedYears.recent[0] : 
          new Date().getFullYear().toString();
        
        // 保留已选择的年份，添加yearGreaterThan参数
        router.push(buildFilterUrl(selectedYears, selectedAreas, selectedTypes, sortBy, searchParams.get('yearLessThan') || undefined, maxRecentYear));
      }
      return;
    }
    
    // 常规年份的处理逻辑
    const newYears = selectedYears.includes(year)
      ? selectedYears.filter(y => y !== year)
      : [...selectedYears, year];
    
    // 保留yearLessThan和yearGreaterThan参数，如果存在的话
    const yearLessThan = searchParams.get('yearLessThan');
    const yearGreaterThan = searchParams.get('yearGreaterThan');
    router.push(buildFilterUrl(newYears, selectedAreas, selectedTypes, sortBy, yearLessThan || undefined, yearGreaterThan || undefined));
  };
  
  const toggleArea = (area: string) => {
    // 桌面端直接应用
    const newAreas = selectedAreas.includes(area)
      ? selectedAreas.filter(a => a !== area)
      : [...selectedAreas, area];
    
    router.push(buildFilterUrl(selectedYears, newAreas, selectedTypes, sortBy));
  };
  
  // 切换类型选中状态
  const toggleType = (typeId: number) => {
    const newTypes = selectedTypes.includes(typeId)
      ? selectedTypes.filter(t => t !== typeId)
      : [...selectedTypes, typeId];
    
    router.push(buildFilterUrl(selectedYears, selectedAreas, newTypes, sortBy));
  };
  
  const handleSortChange = (sort: string) => {
    router.push(buildFilterUrl(selectedYears, selectedAreas, selectedTypes, sort));
  };
  
  // 检查"更早"按钮是否应该高亮
  const isEarlierSelected = () => {
    return searchParams.has('yearLessThan');
  };
  
  // 检查"最新"按钮是否应该高亮
  const isLatestSelected = () => {
    return searchParams.has('yearGreaterThan');
  };
  
  // 处理滚动事件
  const handleScroll = (id: string, event: React.UIEvent<HTMLDivElement>) => {
    const target = event.currentTarget;
    const canScrollLeft = target.scrollLeft > 0;
    const canScrollRight = target.scrollLeft < target.scrollWidth - target.clientWidth;
    
    setScrollStates(prev => ({
      ...prev,
      [id]: { canScrollLeft, canScrollRight }
    }));
  };

  // 滚动容器向左滚动
  const scrollLeft = (id: string) => {
    const container = scrollContainerRefs.current[id];
    if (container) {
      container.scrollBy({ left: -200, behavior: 'smooth' });
    }
  };

  // 滚动容器向右滚动
  const scrollRight = (id: string) => {
    const container = scrollContainerRefs.current[id];
    if (container) {
      container.scrollBy({ left: 200, behavior: 'smooth' });
    }
  };
  
  // 使用useEffect监听滚动容器变化
  useEffect(() => {
    // 获取所有部分的ID
    const sectionIds = [
      '顶级分类',
      childTypes.length > 0 ? '分类' : null,
      '年份',
      '地区',
      '排序'
    ].filter(Boolean).map(title => title!.toLowerCase().replace(/\s+/g, '-'));
    
    // 检查每个部分的滚动状态
    const checkScrollStates = () => {
      sectionIds.forEach(sectionId => {
        const container = scrollContainerRefs.current[sectionId];
        if (container) {
          // 检查媒体查询以确定是否处于大屏模式
          const isLargeScreen = window.matchMedia('(min-width: 768px)').matches;
          
          // 初始化滚动状态
          const canScrollLeft = container.scrollLeft > 0;
          // 在大屏幕上，如果内容可以换行，可能不需要水平滚动
          const canScrollRight = isLargeScreen 
            ? container.scrollWidth > container.clientWidth && container.scrollLeft < container.scrollWidth - container.clientWidth
            : container.scrollWidth > container.clientWidth;
          
          setScrollStates(prev => ({
            ...prev,
            [sectionId]: { canScrollLeft, canScrollRight }
          }));
        }
      });
    };
    
    // 初始检查
    checkScrollStates();
    
    // 添加窗口大小变化事件监听器
    window.addEventListener('resize', checkScrollStates);
    
    // 清理函数
    return () => {
      window.removeEventListener('resize', checkScrollStates);
    };
  }, [childTypes.length, years.length, areas.length]);

  // 渲染水平滚动筛选选项
  const renderHorizontalScrollSection = <T extends string | number | VideoType | {id: string; name: string}>(
    title: string, 
    items: T[], 
    keyExtractor: (item: T) => string,
    labelExtractor: (item: T) => string,
    isSelected: (item: T) => boolean,
    onSelect: (item: T) => void,
    allLabel?: string,
    onClear?: () => void,
  ) => {
    // 为每个部分创建唯一ID
    const sectionId = title.toLowerCase().replace(/\s+/g, '-');
    const isTopLevelCategory = title === '频道';

    return (
      <div className="my-0.5 max-md:px-1">
        <div className="relative">
          {/* 左侧滚动按钮 - 仅在大屏且可以向左滚动时显示 */}
          {scrollStates[sectionId]?.canScrollLeft && (
            <button 
              onClick={() => scrollLeft(sectionId)}
              className="absolute left-[-4px] top-1/2 -translate-y-1/2 z-20 bg-background-card text-white rounded-full p-1 hidden md:max-lg:block shadow-md hover:bg-background-hover"
              aria-label="向左滚动"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
              </svg>
            </button>
          )}
          
          {/* 左侧渐变阴影 - 在可以向左滚动时显示 */}
          {scrollStates[sectionId]?.canScrollLeft && (
            <div className="absolute left-[-8px] top-0 bottom-0 w-8 bg-gradient-to-r from-black to-transparent z-10 pointer-events-none md:hidden"></div>
          )}
          
          {/* 右侧渐变阴影 - 在可以向右滚动时显示 */}
          {scrollStates[sectionId]?.canScrollRight && (
            <div className="absolute right-[-8px] top-0 bottom-0 w-8 bg-gradient-to-l from-black to-transparent z-10 pointer-events-none md:hidden"></div>
          )}
          
          {/* 右侧滚动按钮 - 仅在大屏且可以向右滚动时显示 */}
          {scrollStates[sectionId]?.canScrollRight && (
            <button
              onClick={() => scrollRight(sectionId)}
              className="absolute right-[-4px] top-1/2 -translate-y-1/2 z-20 bg-background-card text-white rounded-full p-1 hidden md:max-lg:block shadow-md hover:bg-background-hover"
              aria-label="向右滚动"
            >
              <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
              </svg>
            </button>
          )}
          
          <div 
            ref={(el) => { scrollContainerRefs.current[sectionId] = el; }}
            onScroll={(e) => handleScroll(sectionId, e)}
            className="overflow-x-auto no-scrollbar overscroll-x-contain relative"
          >
            {/* 使用flex布局，标题固定在左侧，选项填充剩余空间 */}
            <div className="flex px-2 max-sm:px-0 py-1 min-w-min items-start">
              {/* 始终显示标题，不再隐藏在移动端 */}
              <div className="flex-none items-center text-sm font-medium text-gray-300 mr-3 px-3 py-1.5 sm:py-2 rounded-full bg-gradient-to-r from-gray-700/80 to-gray-800/90 whitespace-nowrap min-w-[60px] justify-center border-gray-600/30 flex">
                {title}
              </div>
              
              {/* 选项容器 - 填充剩余宽度 */}
              <div className="flex-1 flex max-md:flex-nowrap md:flex-wrap max-md:space-x-2 md:gap-2 items-center">
                {allLabel && (
                  <button
                    onClick={() => onClear && onClear()}
                    className={`px-3 sm:px-4 py-1.5 sm:py-2 text-sm font-medium rounded-full transition whitespace-nowrap ${
                      !items.some(item => isSelected(item))
                        ? 'bg-red-600 text-white'
                        : 'bg-background-card text-gray-300 hover:bg-background-hover'
                    }`}
                  >
                    {allLabel}
                  </button>
                )}
                {items.map(item => {
                  const commonClassName = `px-3 sm:px-4 py-1.5 sm:py-2 text-sm font-medium rounded-full transition whitespace-nowrap ${
                    isSelected(item)
                      ? 'bg-red-600 text-white'
                      : 'bg-background-card text-gray-300 hover:bg-background-hover'
                  }`;
                  
                  if (isTopLevelCategory && typeof item === 'object' && 'id' in item) {
                    return (
                      <a 
                        key={keyExtractor(item)}
                        href={`/type/${item.id}.html`}
                        className={`${commonClassName} hover:text-gray-300`}
                        onClick={(e) => {
                          e.preventDefault();
                          onSelect(item);
                          const url = `/type/${(item as VideoType).id}.html`;
                          router.push(url);
                        }}
                      >
                        {labelExtractor(item)}
                      </a>
                    );
                  }
                  
                  return (
                    <button
                      key={keyExtractor(item)}
                      onClick={() => onSelect(item)}
                      className={commonClassName}
                    >
                      {labelExtractor(item)}
                    </button>
                  );
                })}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  };
  
  // 获取所有顶级分类（没有父级的分类）
  const getAllTopLevelCategories = () => {
    return allTypes.filter(type => !type.parentId);
  };
  
  // 所有频道
  const topLevelCategories = getAllTopLevelCategories();
  
  // 获取父分类
  const getCurrentParentType = () => {
    // 如果当前分类是顶级分类，返回自身
    const currentType = allTypes.find(type => type.id === currentTypeId);
    if (!currentType) return null;
    
    // 如果有父分类，返回父分类
    if (currentType.parentId) {
      return allTypes.find(type => type.id === currentType.parentId);
    }
    
    // 否则返回自身
    return currentType;
  };
  
  // 获取显示的子分类列表
  const getDisplayChildTypes = () => {
    const parentType = getCurrentParentType();
    
    // 如果找不到父分类，返回当前分类的子分类
    if (!parentType) {
      return childTypes;
    }
    
    // 返回父分类的所有子分类
    return allTypes.filter(type => type.parentId === parentType.id);
  };
  
  // 当前的父分类（可能是当前分类本身，如果它是顶级分类）
  const parentType = getCurrentParentType();
  
  // 需要显示的子分类列表
  const displayChildTypes = getDisplayChildTypes();
  
  // 渲染主要筛选UI
  return (
    <div className="mb-4 bg-background-dark rounded-lg overflow-hidden">
      <div className="md:px-2 py-2 space-y-3">
        {/* 顶级分类选择 - 水平滚动 */}
        <div className="md:pt-1">
          {renderHorizontalScrollSection<VideoType>(
            '频道', 
            topLevelCategories, 
            (item) => item.id.toString(), 
            (item) => item.name, 
            (item) => parentType?.id === item.id, 
            (item) => router.push(`/type/${item.id}.html`),
          )}
        </div>
        
        {/* 分类选择 - 水平滚动 */}
        {displayChildTypes.length > 0 && (
          <div className="md:pt-1 md:mt-1 md:border-t md:border-gray-700/30">
            {renderHorizontalScrollSection<VideoType>(
              '分类', 
              displayChildTypes, 
              (item) => item.id.toString(), 
              (item) => item.name, 
              (item) => currentTypeId === item.id || selectedTypes.includes(item.id), 
              (item) => {
                // 检查当前分类是否已经被选中
                const isSelected = selectedTypes.includes(item.id);
                
                if (parentType) {
                  // 获取新的类型列表
                  const newTypes = isSelected 
                    ? selectedTypes.filter(t => t !== item.id) 
                    : [...selectedTypes, item.id];
                  
                  // 使用buildFilterUrl构建URL
                  router.push(buildFilterUrl(selectedYears, selectedAreas, newTypes, sortBy));
                } else {
                  // 直接切换单个类型
                  toggleType(item.id);
                }
              },
              '全部',
              () => parentType ? router.push(`/type/${parentType.id}.html`) : router.push(`/type/${currentTypeId}.html`), 
            )}
          </div>
        )}
        
        {/* 年份选择 - 水平滚动 */}
        <div className="md:pt-1 md:mt-1 md:border-t md:border-gray-700/30">
          {renderHorizontalScrollSection<string | 'earlier' | 'latest'>(
            '年份', 
            ['latest', ...processedYears.recent, ...(processedYears.hasEarlier ? ['earlier'] : [])], 
            (item) => item === 'earlier' ? 'earlier' : (item === 'latest' ? 'latest' : item), 
            (item) => item === 'earlier' ? '更早' : (item === 'latest' ? '最新' : item), 
            (item) => {
              if (item === 'earlier') return isEarlierSelected();
              if (item === 'latest') return isLatestSelected();
              return selectedYears.includes(item as string);
            }, 
            toggleYear,
            '全部年份',
            () => router.push(buildFilterUrl([], selectedAreas, selectedTypes, sortBy, undefined, undefined)),
          )}
        </div>

        {/* 地区选择 - 水平滚动 */}
        <div className="md:pt-1 md:mt-1 md:border-t md:border-gray-700/30">
          {renderHorizontalScrollSection<string>(
            '地区', 
            areas, 
            (item) => item, 
            (item) => item, 
            (item) => selectedAreas.includes(item), 
            toggleArea,
            '全部地区',
            () => router.push(buildFilterUrl(selectedYears, [], selectedTypes, sortBy, undefined, undefined)),
          )}
        </div>
        
        {/* 排序方式 - 水平滚动 */}
        <div className="md:pt-1 md:mt-1 md:border-t md:border-gray-700/30">
          {renderHorizontalScrollSection<{id: string; name: string}>(
            '排序',
            [
              { id: 'newest', name: '最新' },
              { id: 'hot', name: '热门' },
              { id: 'rating', name: '评分' }
            ],
            (item) => item.id,
            (item) => item.name,
            (item) => sortBy === item.id,
            (item) => handleSortChange(item.id),
          )}
        </div>
      </div>
    </div>
  );
}